package com.twotiger.and.activity.account;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Intent;
import android.graphics.Color;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import app.twotiger.p2p.R;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.mikephil.charting.charts.Chart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendForm;
import com.github.mikephil.charting.components.Legend.LegendPosition;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.HomeActivity;
import com.twotiger.and.activity.WebViewPage;
import com.twotiger.and.activity.account.recharge.RechargePage;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.activity.base.SubTitle;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.BroswerUrl;
import com.twotiger.and.bean.RechargeBank;
import com.twotiger.and.bean.UserAsset;
import com.twotiger.and.util.ArithUtils;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.PromptManager.ReChargeClickListener;

/**
 * 
 * @Description: 
 * 资产详情
 * @Author douxy
 * @Date 2015年8月12日 下午1:34:44
 */
public class TotalAssetPage extends BaseActivity {

    public static final String SHOWWHICH = "showwhich";
    public static final String SHOWWHICH_YESTERDAY = "yesterday";
    public static final String SHOWWHICH_EARN = "earn";
    public static final String SHOWWHICH_ASSET = "asset";

    private final static int GET_ASSERT_SUCCES = 0;
    private final static int GET_ASSERT_FAIL = 1;

    protected static final int OPENPAYMENTSUCCES = 2;
    protected static final int OPENPAYMENTFAIL = 3;

    public final static int GET_CUNBANK_SUCCES = 4;
    private final static int GET_CUNBANK_FAIL = 5;

    private static HashMap<String, String> params;
    private SubTitle subTitle;
    private PieChart pie_chart;
    private TextView tv_assets;
    private TextView tv_1, tv_2, tv_3, tv_4;
    private LinearLayout ll_1, ll_2, ll_3, ll_4;
    private ImageView iv_1, iv_2, iv_3, iv_4;
    private Button btn_charge, btn_invest;

    private UserAsset userAsset;
    private TextView tv1;
    private LinearLayout ll_bottom;
    private String showWhichPage;

    @Override
    protected void processLogic() {
        params = getParm();
        showWhichPage = getIntent().getStringExtra(SHOWWHICH);
        initPage();
        
        //初始化一个灰色圆环
        userAsset = new UserAsset();
        PieData mPieData = getPieData(1, 100);
        showChart(pie_chart, mPieData);

        getuserAsset();
    }

    private void initPage() {
        if (SHOWWHICH_YESTERDAY.equals(showWhichPage)) {
            subTitle.setTitle("昨日收益分布");
            tv1.setText("昨日收益（元）");
            iv_1.setBackgroundResource(R.drawable.rectangle_shape_assets_current);
            iv_2.setBackgroundResource(R.drawable.rectangle_shape_assets_comming);
            ll_3.setVisibility(View.GONE);
            ll_4.setVisibility(View.GONE);
            ll_bottom.setVisibility(View.GONE);
        } else if (SHOWWHICH_EARN.equals(showWhichPage)) {
            subTitle.setTitle("累计赚取分布");
            tv1.setText("累计赚取（元）");
            iv_1.setBackgroundResource(R.drawable.rectangle_shape_assets_current);
            iv_2.setBackgroundResource(R.drawable.rectangle_shape_assets_comming);
            iv_3.setBackgroundResource(R.drawable.rectangle_shape_assets_coupon);
            ll_4.setVisibility(View.GONE);
            ll_bottom.setVisibility(View.GONE);
        } else if (SHOWWHICH_ASSET.equals(showWhichPage)) {
            ll_bottom.setVisibility(View.GONE);
            subTitle.setTitle("总资产");
            tv1.setText("总资产（元）");
        }
    }

    @Override
    protected void setListener() {

        handler = new BaseHandler(this) {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case GET_CUNBANK_SUCCES:
                    Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    Intent intent1 = new Intent();
                    if (result.isOk()) {
                        RechargeBank mRechargeBank = JSON.parseObject(result.data,
                            RechargeBank.class);
                        intent1.setClass(TotalAssetPage.this, RechargePage.class);
                        if (userAsset != null) {
                            intent1.putExtra("CHARGE", userAsset.avaliable);
                        }
                        intent1.putExtra("RECHARGEBANK", mRechargeBank);
                        startNewActivity(intent1, R.anim.push_left_in, R.anim.push_left_out, false);
                    } else {
                        showToast(result.codeDesc);
                    }

                    break;
                case GET_CUNBANK_FAIL:
                    showToast("网络异常");
                    break;
                case OPENPAYMENTSUCCES:
                    Basebean result_open = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_open.isOk()) {
                        BroswerUrl responseinfo = JSONObject.parseObject(result_open.data,
                            BroswerUrl.class);
                        Intent intent2 = new Intent(TotalAssetPage.this, WebViewPage.class);
                        intent2.putExtra("title", "开通三方托管账户");
                        intent2.putExtra("url", responseinfo.getUrl());
                        intent2.putExtra("BUSINESS_TYPE", WebViewPage.TYPE_PAYMENT_REGIST);
                        startNewActivity(intent2, R.anim.push_left_in, R.anim.push_left_out, false);
                    }
                    break;
                case OPENPAYMENTFAIL:
                    showToast("网络异常");
                    break;
                case GET_ASSERT_SUCCES:
                    Basebean result_assert = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_assert.isOk()) {
                        userAsset = JSONObject.parseObject(result_assert.data, UserAsset.class);
                        application.setUserAsset(userAsset);
                        fillData();
                    }
                    break;
                case GET_ASSERT_FAIL:
                    break;
                default:
                    break;
                }

                super.handleMessage(msg);
            }
        };

        btn_charge.setOnClickListener(this);
        btn_invest.setOnClickListener(this);
    }

    protected void fillData() {

        if (SHOWWHICH_YESTERDAY.equals(showWhichPage)) {
            tv_assets.setText(ArithUtils.coverMoneyComma(userAsset.yesDayInt + ""));
            tv_1.setText("活期收益：" + ArithUtils.coverMoneyComma(userAsset.xYesDayInt + ""));
            tv_2.setText("定期收益：" + ArithUtils.coverMoneyComma(userAsset.dYesDayInt + ""));
            PieData mPieData = getPieData(2, 100);
            showChart(pie_chart, mPieData);
        } else if (SHOWWHICH_EARN.equals(showWhichPage)) {
            tv_assets.setText(ArithUtils.coverMoneyComma(userAsset.totalInt + ""));
            tv_1.setText("活期赚取：" + ArithUtils.coverMoneyComma(userAsset.xTotalInt + ""));
            tv_2.setText("定期赚取：" + ArithUtils.coverMoneyComma(userAsset.dTotalInt + ""));
            tv_3.setText("优惠券赚取：" + ArithUtils.coverMoneyComma(userAsset.actTotalInt + ""));
            PieData mPieData = getPieData(3, 100);
            showChart(pie_chart, mPieData);
        } else if (SHOWWHICH_ASSET.equals(showWhichPage)) {
            tv_assets.setText(ArithUtils.coverMoneyComma(userAsset.total + ""));
            tv_1.setText("活期资金：" + ArithUtils.coverMoneyComma(userAsset.xAmount + ""));
            tv_2.setText("可用余额：" + ArithUtils.coverMoneyComma(userAsset.avaliable + ""));
            tv_3.setText("待收本金：" + ArithUtils.coverMoneyComma(userAsset.colctCap + ""));
            tv_4.setText("待收收益：" + ArithUtils.coverMoneyComma(userAsset.colctInt + ""));
            PieData mPieData = getPieData(4, 100);
            showChart(pie_chart, mPieData);
        }
    }

    /**O
     * 获取用户资产
     */
    private void getuserAsset() {
        params.clear();
        params.put("token", getToken());
        getDate(params, Constants.ASSETQUERY, handler, GET_ASSERT_SUCCES, GET_ASSERT_FAIL, true,
            true, false);
    }

    @Override
    protected void findViewById(View view) {
        subTitle = new SubTitle(view) {
            @Override
            protected void clickTitle(View v) {
            }

            @Override
            protected void clickRightBtn(View v) {
            }

            @Override
            protected void cickLeftBtn(View v) {
                onBackPress();
            }
        };
        subTitle.setTitle("总资产");
        subTitle.hideBtns();
        subTitle.title_left_bt.setVisibility(View.VISIBLE);

        tv1 = (TextView) view.findViewById(R.id.tv1);
        pie_chart = (PieChart) view.findViewById(R.id.pie_chart);
        tv_assets = (TextView) view.findViewById(R.id.tv_assets);
        ll_1 = (LinearLayout) view.findViewById(R.id.ll_1);
        iv_1 = (ImageView) view.findViewById(R.id.iv_1);
        tv_1 = (TextView) view.findViewById(R.id.tv_1);
        ll_2 = (LinearLayout) view.findViewById(R.id.ll_2);
        iv_2 = (ImageView) view.findViewById(R.id.iv_2);
        tv_2 = (TextView) view.findViewById(R.id.tv_2);
        ll_3 = (LinearLayout) view.findViewById(R.id.ll_3);
        iv_3 = (ImageView) view.findViewById(R.id.iv_3);
        tv_3 = (TextView) view.findViewById(R.id.tv_3);
        ll_4 = (LinearLayout) view.findViewById(R.id.ll_4);
        iv_4 = (ImageView) view.findViewById(R.id.iv_4);
        tv_4 = (TextView) view.findViewById(R.id.tv_4);
        ll_bottom = (LinearLayout) view.findViewById(R.id.ll_bottom);

        btn_charge = (Button) view.findViewById(R.id.btn_charge);
        btn_invest = (Button) view.findViewById(R.id.btn_invest);

    }

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.total_assert, null);
        return view;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.btn_charge:
            if (!hasOpenThirdAct()) {
                PromptManager.showConfirmAlertCommon(TotalAssetPage.this, 0, "",
                    "您还未开通汇付天下托管账号，继续开通", "取消", "继续", true, new ReChargeClickListener() {

                        @Override
                        public void onClickConfirm() {

                        }

                        @Override
                        public void onClickCancel() {
                            openpayment();
                        }
                    });

                return;
            }
            toCharge();
            break;
        case R.id.btn_invest:
            startNewActivity(new Intent(TotalAssetPage.this, HomeActivity.class).putExtra("BUTTON",
                R.id.radio_btn2), R.anim.push_left_in, R.anim.push_left_out, true);
            break;
        default:
            break;

        }
    }

    private void toCharge() {
        params.clear();
        params.put("token", getToken());
        getDate(params, Constants.RECHARGEBANKQUERY, handler, GET_CUNBANK_SUCCES,
            GET_CUNBANK_FAIL, true, true, false);
    }

    public void openpayment() {
        params.clear();
        params.put("token", getToken());
        getDate(params, Constants.REGISTHF, handler, OPENPAYMENTSUCCES, OPENPAYMENTFAIL, true,
            true, false);
    }

    @Override
    protected void onBackPress() {
        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    /**  
     *   
     * @param count 分成几部分  
     * @param range  
     */
    private PieData getPieData(int count, float range) {

        ArrayList<String> xValues = new ArrayList<String>(); //xVals用来表示每个饼块上的内容    

        for (int i = 0; i < count; i++) {
            //            xValues.add("Quarterly" + (i + 1)); //饼块上显示成Quarterly1, Quarterly2, Quarterly3, Quarterly4
            xValues.add("");
        }

        ArrayList<Entry> yValues = new ArrayList<Entry>(); //yVals用来表示封装每个饼块的实际数据    
        ArrayList<Integer> colors = new ArrayList<Integer>();

        // 饼图数据    
        /**  
         * 将一个饼形图分成四部分， 四部分的数值比例为14:14:34:38  
         * 所以 14代表的百分比就是14%   
         */
        if (SHOWWHICH_YESTERDAY.equals(showWhichPage)) {
            float quarterly1 = (float) userAsset.xYesDayInt;
            float quarterly2 = (float) userAsset.dYesDayInt;
            if(quarterly1 != 0){
                yValues.add(new Entry(quarterly1, 0));
                colors.add(Color.rgb(255, 129, 32));
            }
            if(quarterly2 != 0){
                yValues.add(new Entry(quarterly2, 0));
                colors.add(Color.rgb(59, 169, 222));
            }
        } else if (SHOWWHICH_EARN.equals(showWhichPage)) {
            float quarterly1 = (float) userAsset.xTotalInt;
            float quarterly2 = (float) userAsset.dTotalInt;
            float quarterly3 = (float) userAsset.actTotalInt;
            if(quarterly1 != 0){
                yValues.add(new Entry(quarterly1, 0));
                colors.add(Color.rgb(255, 129, 32));
            }
            if(quarterly2 != 0){
                yValues.add(new Entry(quarterly2, 0));
                colors.add(Color.rgb(59, 169, 222));
            }
            if(quarterly3 != 0){
                yValues.add(new Entry(quarterly3, 0));
                colors.add(Color.rgb(255, 127, 126));
            }
        } else if (SHOWWHICH_ASSET.equals(showWhichPage)) {
            float quarterly1 = (float) userAsset.xAmount;
            float quarterly2 = (float) userAsset.avaliable;
            float quarterly3 = (float) userAsset.colctCap;
            float quarterly4 = (float) userAsset.colctInt;
            if(quarterly1 != 0){
                yValues.add(new Entry(quarterly1, 0));
                colors.add(Color.rgb(235, 109, 33));
            }
            if(quarterly2 != 0){
                yValues.add(new Entry(quarterly2, 0));
                colors.add(Color.rgb(230, 175, 10));
            }
            if(quarterly3 != 0){
                yValues.add(new Entry(quarterly3, 0));
                colors.add(Color.rgb(57, 171, 225));
            }
            if(quarterly4 != 0){
                yValues.add(new Entry(quarterly4, 0));
                colors.add(Color.rgb(173, 88, 233));
            }
        }
        
        if(yValues.size() == 0 && colors.size() == 0){
            yValues.add(new Entry(100, 0));
            colors.add(Color.rgb(162, 162, 162));
        }
        
        //y轴的集合    
        PieDataSet pieDataSet = new PieDataSet(yValues, "Quarterly Revenue 2014"/*显示在比例图上*/);
        if(yValues.size() > 1){
            pieDataSet.setSliceSpace(1.0f); //设置个饼状图之间的距离    
        }else{ //只有一个颜色圈的话不需要有分割线
            pieDataSet.setSliceSpace(0.0f); //设置个饼状图之间的距离    
        }

        pieDataSet.setColors(colors);

        pieDataSet.setValueTextColor(Color.TRANSPARENT); //圆饼上数据的显示颜色

        DisplayMetrics metrics = getResources().getDisplayMetrics();
        float px = 5 * (metrics.densityDpi / 160f);
        pieDataSet.setSelectionShift(0); // 选中态多出的长度    

        PieData pieData = new PieData(xValues, pieDataSet);

        return pieData;
    }

    private void showChart(PieChart pieChart, PieData pieData) {
        pieChart.setHoleColorTransparent(true);
        
        pieChart.setOnTouchListener(new ChartTouchListener<Chart<?>>(pieChart) {

            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                return false;
            }
        });

        pieChart.setHoleRadius(60f); //半径    
        pieChart.setTransparentCircleRadius(0f); // 半透明圈    
        //pieChart.setHoleRadius(0)  //实心圆    

        pieChart.setDescription("");

        // mChart.setDrawYValues(true);    
        pieChart.setDrawCenterText(false); //饼状图中间可以添加文字    

        pieChart.setDrawHoleEnabled(true); //饼状图中间大洞可见

        pieChart.setRotationAngle(-90); // 初始旋转角度    

        // draws the corresponding description value into the slice    
        // mChart.setDrawXValues(true);    

        // enable rotation of the chart by touch    
        pieChart.setRotationEnabled(false); // 可以手动旋转    

        // display percentage values    
        pieChart.setUsePercentValues(false); //显示成百分比    
        // mChart.setUnit(" €");    
        // mChart.setDrawUnitsInChart(true);    

        // add a selection listener    
        //          mChart.setOnChartValueSelectedListener(this);    
        // mChart.setTouchEnabled(false);    

        //          mChart.setOnAnimationListener(this);    

        pieChart.setCenterText("Quarterly Revenue"); //饼状图中间的文字    

        //设置数据    
        pieChart.setData(pieData);

        // undo all highlights    
        //          pieChart.highlightValues(null);    
        //          pieChart.invalidate();    

        Legend mLegend = pieChart.getLegend(); //设置比例图    
        mLegend.setPosition(LegendPosition.BELOW_CHART_LEFT); //最右边显示    
        mLegend.setForm(LegendForm.SQUARE); //设置比例图的形状，默认是方形    
        mLegend.setXEntrySpace(7f);
        mLegend.setYEntrySpace(5f);
        mLegend.setEnabled(false);

        pieChart.animateXY(0, 0); //设置动画    
        // mChart.spin(2000, 0, 360);    
    }

}
